import numpy as np  # 矩阵操作
import pandas as pd # SQL数据处理

from sklearn.metrics import r2_score  #评价回归预测模型的性能

import matplotlib.pyplot as plt   #画图
import seaborn as sns

# 图形出现在Notebook里而不是新窗口
#%matplotlib inline

# path to where the data lies
#dpath = r'D:\\'
data = pd.read_csv("day.csv")
y = data['cnt']
C = data.drop('cnt', axis = 1)
X=C.drop(['dteday','yr','season','casual','registered'],axis=1)
#X=C.drop(['dteday','instant','season','yr','mnth','holiday','weekday','workingday','weathersit','casual','registered'],axis=1)
columns = X.columns
'''X_train=X.ix[:364]
X_test=X.ix[365:]
y_train=y.ix[:364].values
y_test=y.ix[365:].values
#print(y_train,y_test)'''

from sklearn.model_selection import train_test_split
# 随机采样50%的数据构建测试样本，其余作为训练样本
X_train, X_test, y_train, y_test = train_test_split(X, y, random_state=42, test_size=0.5)

from sklearn.preprocessing import StandardScaler
ss_X = StandardScaler()
ss_y = StandardScaler()
X_train = ss_X.fit_transform(X_train)
X_test = ss_X.transform(X_test)
#y_train = ss_y.fit_transform(y_train.reshape(-1, 1))
#y_test = ss_y.transform(y_test.reshape(-1, 1))

from sklearn.linear_model import LinearRegression

# 使用默认配置初始化
lr = LinearRegression()

# 训练模型参数
lr.fit(X_train, y_train)

# 预测
y_test_pred_lr = lr.predict(X_test)
y_train_pred_lr = lr.predict(X_train)


# 看看各特征的权重系数，系数的绝对值大小可视为该特征的重要性
fs = pd.DataFrame({"columns":list(columns), "coef":list((lr.coef_.T))})
fs.sort_values(by=['coef'],ascending=False)

print ('The r2 score of LinearRegression on test is', r2_score(y_test, y_test_pred_lr))
#训练集
print( 'The r2 score of LinearRegression on train is', r2_score(y_train, y_train_pred_lr))




from sklearn.linear_model import  RidgeCV

#设置超参数（正则参数）范围
alphas = [ 0.01, 0.1, 1, 10,100]
#n_alphas = 20
#alphas = np.logspace(-5,2,n_alphas)

#生成一个RidgeCV实例
ridge = RidgeCV(alphas=alphas, store_cv_values=True)

#模型训练
ridge.fit(X_train, y_train)

#预测
y_test_pred_ridge = ridge.predict(X_test)
y_train_pred_ridge = ridge.predict(X_train)


# 评估，使用r2_score评价模型在测试集和训练集上的性能
print( 'The r2 score of RidgeCV on test is', r2_score(y_test, y_test_pred_ridge))
print( 'The r2 score of RidgeCV on train is', r2_score(y_train, y_train_pred_ridge))


from sklearn.linear_model import LassoCV

#设置超参数搜索范围
alphas = [ 0.01, 0.1, 1, 10,100]

#生成一个LassoCV实例
#lasso = LassoCV(alphas=alphas)
lasso = LassoCV()

#训练（内含CV）
lasso.fit(X_train, y_train)

#测试
y_test_pred_lasso = lasso.predict(X_test)
y_train_pred_lasso = lasso.predict(X_train)


# 评估，使用r2_score评价模型在测试集和训练集上的性能
print ('The r2 score of LassoCV on test is', r2_score(y_test, y_test_pred_lasso))
print( 'The r2 score of LassoCV on train is', r2_score(y_train, y_train_pred_lasso))

#
#X_train=X[X.instant<=365]
#X_test=X[X.instant>365]

#y_train1=data[data.instant<=365]
#y_train=y_train1['cnt'].values

#y_test1=data[data.instant>365]
#y_test=y_test1['cnt'].values


#y_test=y[y.instant>365]

#print (X_train)
#print (y_train,y_test)

